package com.cartoonrabbit.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cartoonrabbit.pojo.InviteRecord;
import com.cartoonrabbit.mapper.InviteRecordMapper;
import com.cartoonrabbit.pojo.User;
import com.cartoonrabbit.service.IInviteRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cartoonrabbit.service.IUserService;
import com.cartoonrabbit.vo.RespBean;
import com.cartoonrabbit.vo.RespPageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiuTeng
 * @since 2023-01-09
 */
@Service
public class InviteRecordServiceImpl extends ServiceImpl<InviteRecordMapper, InviteRecord> implements IInviteRecordService {

    @Autowired
    private InviteRecordMapper inviteRecordMapper;
    @Autowired
    private IUserService userService;

    /**
     * 创建要求记录
     * @param openid
     * @param inviteId
     */
    @Override
    @Transactional
    public void createInviteRecord(String openid, String inviteId) {
        InviteRecord inviteRecord=new InviteRecord();
        inviteRecord.setInviteId(RandomUtil.randomString(15));
        inviteRecord.setInviteOpenid(inviteId);
        inviteRecord.setInvitedOpenid(openid);
        Long money=getRandomMoney();
        inviteRecord.setAwardMoney(money);
        save(inviteRecord);
        User inviteUser = userService.getById(inviteId);
        inviteUser.setBalance(inviteUser.getBalance()+money);
        inviteUser.setInvitePeopleNum(inviteUser.getInvitePeopleNum()+1);
        userService.updateById(inviteUser);
    }

    @Override
    public RespBean inviteList(Integer currentPage, Integer size, String openId) {

        Page page=new Page(currentPage,size);
        Page<InviteRecord> inviteRecordPage=inviteRecordMapper.inviteList(page,openId);
        RespPageBean respPageBean = new RespPageBean();
        respPageBean.setCurrentPage(inviteRecordPage.getCurrent());
        respPageBean.setSize(inviteRecordPage.getSize());
        respPageBean.setTotal(inviteRecordPage.getTotal());
        respPageBean.setData(inviteRecordPage.getRecords());
        return RespBean.success("SUCCESS",respPageBean);
    }

    public Long getRandomMoney() {
        //设置奖励金额,奖励金额在0.05-1元
        int randomInt = RandomUtil.randomInt(0, 100);
        Integer money=0;
        if (randomInt<96){//5~30
            int ran2 = RandomUtil.randomInt(0, 100);
            if (ran2<90){
                money=RandomUtil.randomInt(5,20);
            }else {
                money=RandomUtil.randomInt(20,31);
            }
        }else if (randomInt<99){//30-50
            money=RandomUtil.randomInt(30,51);
        }else if (randomInt<100){//50-100
            money=RandomUtil.randomInt(50,101);
        }
        return money.longValue();
    }

}
